package com.violet.detective.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.violet.detective.entity.Workorder;
import com.violet.detective.entity.Repair;
import com.violet.detective.entity.Defect;
import com.violet.detective.entity.Equipment;
import com.violet.detective.mapper.DefectMapper;
import com.violet.detective.mapper.RepairMapper;
import com.violet.detective.mapper.WorkorderMapper;
import com.violet.detective.search.EquipmentSearchParameter;
import com.violet.detective.service.EquipmentService;
import com.violet.detective.mapper.EquipmentMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.UUID;
import java.util.stream.Collectors;
import java.util.List;

/**
* @author 21145
* @description 针对表【Equipment】的数据库操作Service实现
* @createDate 2023-09-04 21:36:49
*/
@Service
public class EquipmentServiceImpl extends ServiceImpl<EquipmentMapper, Equipment>
    implements EquipmentService{

    @Resource
    EquipmentMapper equipmentMapper;

    @Resource
    DefectMapper defectMapper;

    @Resource
    RepairMapper repairMapper;

    @Resource
    WorkorderMapper workorderMapper;

    public boolean addEquipment(Equipment newEquipment, MultipartFile file) throws IOException {
        String originalFileName = file.getOriginalFilename();
        assert originalFileName != null;
        int index = originalFileName.lastIndexOf('.') + 1;
        String type = originalFileName.substring(index);
        String filePath = "D:\\IMG1";
        String newFileName = UUID.randomUUID() + originalFileName;
        File targetFile = new File(filePath, newFileName);
        file.transferTo(targetFile);
        newEquipment.setPicPath(newFileName);
        if(type.equals("jpg")) {
            int result = equipmentMapper.insert(newEquipment);
            return result > 0;
        }
        return false;
    }

    public void showImage(String imageName, HttpServletResponse response) throws IOException {
        String imagePath = "D:\\IMG1\\" + imageName;
        FileInputStream fileInputStream = new FileInputStream(imagePath);
        byte[] bytes = new byte[fileInputStream.available()];
        fileInputStream.read(bytes, 0, fileInputStream.available());

        response.setContentType("image/jpg"); // 或者 "image/png"，取决于你的图像类型
        OutputStream outputStream = response.getOutputStream();
        outputStream.write(bytes);
        outputStream.flush();
        outputStream.close();
        fileInputStream.close();
    }

    public boolean editEquipment(Equipment updatedEquipment) {
        Equipment existingEquipment = equipmentMapper.selectById(updatedEquipment.getId());
        if (existingEquipment == null)
            return false;
        if (updatedEquipment.getName() != null)
            existingEquipment.setName(updatedEquipment.getName());
        if (updatedEquipment.getUnit() != null)
            existingEquipment.setUnit(updatedEquipment.getUnit());
        if (updatedEquipment.getMajor() != null)
            existingEquipment.setMajor(updatedEquipment.getMajor());
        int result = equipmentMapper.updateById(updatedEquipment);
        return result > 0;
    }

    public boolean deleteEquipment(Integer id) throws Exception {
        int defectCount = defectMapper.selectCount(new QueryWrapper<Defect>().eq("equipmentId", id));
        int repairCount = repairMapper.selectCount(new QueryWrapper<Repair>().eq("equipmentId", id));
        int workOrderCount = workorderMapper.selectCount(new QueryWrapper<Workorder>().eq("equipmentId", id));

        if(defectCount > 0 || repairCount > 0 || workOrderCount > 0){
            throw new Exception("该设备已被使用, 无法删除");
        }

        int result = equipmentMapper.deleteById(id);
        return result > 0;
    }

    public Equipment getEquipmentById (Integer id) {
        return equipmentMapper.selectById(id);
    }

    public Equipment searchEquipments(Integer id) {
        return equipmentMapper.selectById(id);
    }

    public List<Equipment> searchEquipments(EquipmentSearchParameter searchParameter) {
        QueryWrapper<Equipment> query = new QueryWrapper<>();
        if (searchParameter.getId() != null)
            query.eq("id", searchParameter.getId());
        if (searchParameter.getName() != null)
            query.like("name", searchParameter.getName());
        if (searchParameter.getUnit() != null)
            query.like("unit", searchParameter.getUnit());
        if (searchParameter.getMajor() != null)
            query.like("major", searchParameter.getMajor());

        return equipmentMapper.selectList(query);
    }

    public Page<Equipment> searchEquipments(EquipmentSearchParameter searchParameter, int pageNum, int pageSize) {
        QueryWrapper<Equipment> query = new QueryWrapper<>();
        if (searchParameter.getId() != null)
            query.eq("id", searchParameter.getId());
        if (searchParameter.getName() != null)
            query.like("name", searchParameter.getName());
        if (searchParameter.getUnit() != null)
            query.like("unit", searchParameter.getUnit());
        if (searchParameter.getMajor() != null)
            query.like("major", searchParameter.getMajor());

        Page<Equipment> page = new Page<>(pageNum, pageSize);
        return equipmentMapper.selectPage(page, query);
    }

    public List<Integer> searchEquipmentIdsByName(String name) {
        QueryWrapper<Equipment> wrapper = new QueryWrapper<>();
        wrapper.lambda().like(Equipment::getName, name);
        List<Equipment> equipments = equipmentMapper.selectList(wrapper);

        return equipments.stream()
                .map(Equipment::getId)
                .collect(Collectors.toList());
    }

    public List<Integer> searchEquipmentIdsByMajor(String major) {
        QueryWrapper<Equipment> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(Equipment::getMajor, major);
        List<Equipment> equipments = equipmentMapper.selectList(wrapper);

        return equipments.stream()
                .map(Equipment::getId)
                .collect(Collectors.toList());
    }

    public List<Equipment> findAllEquipments() {
        return equipmentMapper.selectList(null);
    }

    public Page<Equipment> findAllEquipments(int pageNum, int pageSize) {
        Page<Equipment> page = new Page<>(pageNum, pageSize);
        return equipmentMapper.selectPage(page, null);
    }

}




